package com.koron.css2.serviceManage.impl;

import com.koron.css2.ApplicationConfig;
import com.koron.css2.ServerInterface;
import com.koron.css2.serviceManage.bean.QuartzBean;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.QuartzMapper;
import com.koron.css2.serviceManage.queryBean.JobQueryBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 查询定时任务 最后执行时间
 */
public class JobSelectTime implements ServerInterface{

	
	private Logger log = LogManager.getLogger(JobSelectTime.class);
	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		@SuppressWarnings("rawtypes")
		MessageBean<QuartzBean> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", QuartzBean.class);

		try {
			JobQueryBean bean = JsonUtils.objectToPojo(req.getData(), JobQueryBean.class);
			QuartzMapper mapper = factory.getMapper(QuartzMapper.class,"_default");

			QuartzBean quartzBean = mapper.selectTime(bean, ApplicationConfig.getQuartzPrefix());
			if (quartzBean!=null) {
				//转换日期格式
				if (quartzBean.getNextFireTime() != null)
					quartzBean.setNextFireTime(timeStampToTime(quartzBean.getNextFireTime()));
				if (quartzBean.getPrevFireTime() != null)
					quartzBean.setPrevFireTime(timeStampToTime(quartzBean.getPrevFireTime()));

				if ("WAITING".equalsIgnoreCase(quartzBean.getTriggerState()))
					quartzBean.setStateName("等待");
				else if ("PAUSED".equalsIgnoreCase(quartzBean.getTriggerState()))
					quartzBean.setStateName("暂停");
				else if ("ACQUIRED".equalsIgnoreCase(quartzBean.getTriggerState()))
					quartzBean.setStateName("正常执行");
				else if ("BLOCKED".equalsIgnoreCase(quartzBean.getTriggerState()))
					quartzBean.setStateName("阻塞");
				else if ("ERROR".equalsIgnoreCase(quartzBean.getTriggerState()))
					quartzBean.setStateName("错误");
				else
					quartzBean.setStateName("");
			}
			info.setData(quartzBean);
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		return info;
	}
	


	/**
	 * 时间戳转换成日期格式字符串
	 * @param seconds 精确到秒的字符串
	 * @return
	 */
	public static String timeStampToTime(String seconds) {
		String format = "yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(new Date(Long.valueOf(seconds)));
	}
}
